#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""诗词库操作
建立诗词库
按各种条件查询诗词库
"""
from PoetryModel import PoetryModel
from PoetryExcel import PoetryReadExcel
from Base import Base
from numpy import random


class QuestionStore(Base):
    def __init__(self):
        super(QuestionStore, self).__init__()
        self.petx = PoetryReadExcel.instance()
        # 各种消息
        self.error_msg = ""
        self.msg = ""
        # 加载问题科目集合
        self.question_subject = []  # 问题科目集合
        for key in self.cfg['file']:
            if self.cfg.getboolean('file', key):
                self.question_subject.append(key)
        # 缩写文件名 后面看着清晰易懂
        self.poetry_file_name = self.cfg['path']['poetry_file_path'] + '/' + self.cfg['poetry_file']['poetry_file_name']
        self.question_file_name = self.cfg['path']['question_file_path'] + '/' + self.cfg['question_file']['question_file_name']
        # 加载诗词库
        if self.cfg.getboolean('file', 'poetry_file'):
            self.author_dynasty_dict = self.petx.get_many_short_long_cols(self.poetry_file_name,
                                                                          self.cfg['poetry_file']['sheet_author_dynasty_name'])
            self.flower_orders = self.petx.get_col(self.cfg['poetry_file']['sheet_flower_order_name'])  # 获取飞花令字库
            self.new_flower_orders = self.petx.get_many_short_long_cols(self.poetry_file_name,
                                                                        self.cfg['poetry_file']['sheet_new_flower_order_name'])  # 获取高级飞花令字库
            self.idioms = []
            if self.cfg.getboolean('question_type', 'get_sentence_by_idiom'):  # 如果有根据成语获取诗句的题则加载成语库
                idioms_all = self.petx.get_many_cols(self.poetry_file_name, self.cfg['poetry_file']['sheet_idiom_name'])
                for idiom in idioms_all['成语']:
                    if len(idiom) == 4:  # 只使用4字成语看起来比较整齐
                        self.idioms.append(idiom)
            self.poetry_store = {}  # 诗词实体类集合，key为诗词名称便于查询。
            self.poetry_name_box = []  # 用于保存诗词名称保证诗词不重复
            self.get_poetry_store()
        # 加载独立问题库
        if self.cfg.getboolean('file', 'question_file'):
            self.questions = []  # 问题集合
            self.question_no_box = []  # 问题编号表保证诗词不重复
            self.get_question_store()
        # 写日志
        self.run_info('************************************************')
        self.run_info('又开始玩游戏了！')

    @staticmethod
    def instance():
        global inst
        try:
            inst
        except:
            inst = QuestionStore()
        return inst

    # 从Excel中直接加载诗词库
    def get_poetry_store(self):
        self.msg = self.msg + self.petx.msg
        self.error_msg = self.error_msg + self.petx.error_msg
        poetrys_temp = self.petx.excel_to_poetry_list()
        for item in poetrys_temp:
            if item[1] == "no":
                item[1] = ""
                item1 = ""
            else:
                item1 = "·" + item[1]
            dynasty = self.get_dynasty_by_author(item[2])
            poetry_name = "【" + item[0] + item1 + "】" + item[2] + '(' + dynasty + ')'
            poetry = PoetryModel(poetry_name, item, dynasty, self.flower_orders, self.new_flower_orders, self.idioms)
            self.poetry_store[poetry_name] = poetry
            self.poetry_name_box.append(poetry_name)

    # 加载问题独立库
    def get_question_store(self):
        # 获取加载的科目列表
        questions_subject = {}
        ex_question_subject = self.petx.get_many_cols(self.question_file_name,
                                                      self.cfg['question_file']['sheet_table_of_contents_name'])
        for no in range(0, len(ex_question_subject['是否加载'])):
            if ex_question_subject['是否加载'][no] == 'Y':
                questions_subject[ex_question_subject['编号'][no]] = ex_question_subject['题库'][no]
        # 在每个列表中加载要加载的题目
        for key in questions_subject:
            ex_question = self.petx.get_many_cols(self.question_file_name, questions_subject[key])
            for no in range(0, len(ex_question['是否加载'])):
                if ex_question['是否加载'][no] == 'Y':
                    question = {'no': key + '_' + ex_question['编号'][no],
                                'subject': 'question',
                                'question': ex_question['问题'][no],
                                'answer': ex_question['答案'][no],
                                'explain': ex_question['解析'][no]}
                    self.questions.append(question)
                    self.question_no_box.append(key + '_' + ex_question['编号'][no])

    # 根据诗人获取朝代
    def get_dynasty_by_author(self, author):
        for dynasty in self.author_dynasty_dict:
            if author in self.author_dynasty_dict[dynasty]:
                return dynasty
        self.error('诗人[' + author + ']没有找到对应朝代！')

    def print_poetry(self, print_level=0):
        for item in self.poetry_store:
            self.poetry_store[item].print_content(print_level)
            print("   ")

    # 获取诗词内容
    def get_poetry_content(self, full_name):
        return self.poetry_store[full_name].get_content()

    # 获取问题入口
    def get_question(self):
        subject = random.choice(self.question_subject)
        self.run_info('题目类型：' + subject)
        if subject == 'question_file':
            return self.get_china_question()
        elif subject == 'poetry_file':
            return self.get_poetry_question()
        else:
            self.error('[' + subject + ']是个啥题目类型？')

    # 获取诗词生成的问题
    def get_poetry_question(self):
        if not self.cfg.getboolean('other', 'question_isRepeat'):  # 诗词在每个循环内不重复
            if self.poetry_name_box.__len__() == 0:
                for item in self.poetry_store:
                    self.poetry_name_box.append(item)
            poetry_no = random.choice(self.poetry_name_box)
            self.run_info('这次选择的诗词是： ' + poetry_no)
            self.poetry_name_box.remove(poetry_no)
        else:
            poetry_no = random.choice(list(self.poetry_store))
        poetry = self.poetry_store[poetry_no]
        question = poetry.question()
        if question is None:
            question = self.get_poetry_question()
        return question

    # 获取所有诗的所有问题
    def get_all_poetrys_all_questions(self):
        all_questions = [{'no': '名称', 'type': '问题类型', 'question': '问题', 'answer': '答案', 'explain': '解释'}]
        # self.debug("总唐诗数：" + str(len(self.poetry_store)))
        for poetry in self.poetry_store:
            questions = self.poetry_store[poetry].get_all_questions()
            # self.run_info(poetry + '包含的问题数：' + str(len(questions)))
            all_questions = all_questions + questions
            # break
        return all_questions

    # 获取独立问题
    def get_china_question(self):
        if not self.cfg.getboolean('other', 'question_isRepeat'):
            if self.question_no_box.__len__() == 0:
                for item in self.questions:
                    self.question_no_box.append(item['no'])
        no = random.choice(self.question_no_box)
        self.run_info('这次选择的问题编号是： ' + no)
        self.question_no_box.remove(no)
        china_question = {}
        for question in self.questions:
            if question['no'] == no:
                china_question = question
                break
        return china_question

    # 搜索诗词
    def select_from_poetry(self, select_str, model):
        if model not in ['title', 'author', 'dynasty', 'content', 'new_flowers', 'tag']:
            self.error('搜索模式[' + model + ']错误！')
        result = []
        for name in self.poetry_store:
            result_poetry = self.poetry_store[name].select_from_poetry(select_str, model)
            for r in result_poetry:
                result.append(r)
        result_str = '搜索到的诗词如下：'
        for r in result:
            result_str = result_str + '\n' + r
        result_str = result_str + '\n共' + str(len(result)) + '项'
        return result_str


if __name__ == "__main__":
    p = QuestionStore()
    # q = p.get_question()
    for i in p.idioms:
        if len(i) == 4:
            print(i)
    # for item in p.poetry_store:
    #     print(p.poetry_store[item].full_name)
    # re = p.select_from_poetry('风', 'content')
    # print(re)
    # for item in p.questions:
    #     print(item)
